$(document).ready(function() {
    refreshListing();
    
    /**
     * 刷新或搜索
     */
    $('body').delegate('.action-refresh', 'click', function(){
        $('#content_listing_archive').datagrid('reload');
        return false;
    });
    
    /**
     * 搜索对回车的支持
     */
    $("input[name=key]").on('keypress', function (event) {
        if (event.which == '13' && $(this).val()) {
            $('#content_listing_archive').datagrid('reload');
            return false;
        }
    });
    
    /**
     * datepicker
     */
    $(".datepicker-input").each(function(){ $(this).datepicker({language:"zh-CN", autoclose:true});});
    
    /**
     * 删除档案 - 处理待删除档案号
     */
    $('#content_listing_archive').on('click', '.action-select-confirm', function(){
        $('input[name=delete_archive_sn]:last').val($(this).data('sn'));
    });
    
    /**
     * 选择删除二次确认人 - 处理选中状态
     */
    $('#modal_select_confirm').on('click', '.item-user', function(){
        if (! $(this).hasClass('active')) {
            $('.item-user').removeClass('active');
            $(this).addClass('active');
        } else {
            $(this).removeClass('active');
        }
    });
    
    /**
     * 选择删除二次确认人 - 提交
     */
    $('#modal_select_confirm').on('click', '#submit_select_user', function(){
        /* 必须选择一个二次确认人 */
        var userid = null;
        $('.item-user').each(function(){
            if ($(this).hasClass('active')) {
                userid = $(this).data('userid');
            }
        });
        if (! userid) {
            alert('请选择一个二次确认人！');
            return false;
        }
        
        /* 删除确认 */
        var str_confirm = '确定要申请删除该案件吗？';
        if (! confirm(str_confirm)) {
            return false;
        }
        
        /* ajax 执行删除 */
        var sn = $('input[name=delete_archive_sn]:last').val();
        $.ajax({
            type:'post',
            url:'/archiveadmin/content/deleteArchive',
            data:'userid=' + userid + '&sn=' + sn,
            dataType:'json',
            timeout:60000,
            success:function(data){
                if (data.status == 0) {
                    alert('删除申请提交成功');
                    $('#content_listing_archive').datagrid('reload');
                    $('#modal_select_confirm').modal('hide');
                } else {
                    alert(data.error);
                }
                return false;
            }
        });
    });
});


/**
 * 获取案件列表
 */
function refreshListing() {
    /* fuelux datagrid */
    var DataGridDataSource = function (options) {
        this._formatter = options.formatter;
        this._columns = options.columns;
        this._delay = options.delay;
    };
    
    DataGridDataSource.prototype = {
        columns: function () {
            return this._columns;
        },
        data: function (options, callback) {
            var url = '/archiveadmin/content';
            var self = this;
            
            setTimeout(function () {
                data = $.extend(true, [], self._data);
                $.ajax(url, {
                    data: {
                        rstype:"json",
                        pageIndex: options.pageIndex,
                        pageSize: options.pageSize,
                        time_start:$('input[name=time_start]').val(),
                        time_end:$('input[name=time_end]').val(),
                        category_name:$('select[name=category_name]').val(),
                        department_name:$('select[name=department_name]').val(),
                        dot:$('select[name=dot]').val(),
                        key:$('input[name=key]').val()
                    },
                    dataType: 'json',
                    async: true,
                    type: 'GET'
                }).done(function (response) {
                    data = response.data.content;
                    if (! data) {
                        return false;
                    }
                    
                    var count=response.data.count;//设置data.total
                    // PAGING
                    var startIndex = options.pageIndex * options.pageSize;
                    var endIndex = startIndex + options.pageSize;
                    var end = (endIndex > count) ? count : endIndex;
                    var pages = Math.ceil(count / options.pageSize);
                    var page = options.pageIndex + 1;
                    var start = startIndex + 1;
                    
                    if (self._formatter) self._formatter(data);
                    
                    callback({ data: data, start: start, end: end, count: count, pages: pages, page: page });
                }).fail(function (e) {
                
                });
            }, self._delay);
        }
    };
    
    $('#content_listing_archive').datagrid({
        dataSource: new DataGridDataSource({
            // Column definitions for Datagrid
            columns: [
//                {
//                    property: 'checkbox',
//                    label: '<input type="checkbox" />'
//                },
                {
                    property: 'a',
                    label: ''
                },
                {
                    property: 'sn',
                    label: '编号',
                    sortable: false
                },
                {
                    property: 'title',
                    label: '案件名称',
                    sortable: false
                },
                {
                    property: 'department_name',
                    label: '承办部门',
                    sortable: false
                },
                {
                    property: 'category_name',
                    label: '案件类型',
                    sortable: false
                },
                {
                    property: 'label',
                    label: '标签',
                    sortable: false
                },
                {
                    property: 'count_card',
                    label: '行动次数',
                    sortable: false
                },
                {
                    property: 'str_status',
                    label: '状态',
                    sortable: false
                },
                {
                    property: 'ctime',
                    label: '创建时间',
                    sortable: false
                },
                {
                    property: 'mtime',
                    label: '更新时间',
                    sortable: false
                },
                {
                    property: 'action',
                    label: '操作',
                    sortable: false
                }
            ],
            formatter: function (items) {
                $.each(items, function (index, item) {
                    /* 处理全选 */
//                    item.checkbox = '<input type="checkbox" name="post[]" class="select-single" value="' + item.pID + '">';
                    
                    /* 查看详情 */
                    item.a = '<a class="btn btn-xs btn-info btn-rounded" href="/archiveadmin/content/detail?_id=' + item._id + '"' + 
                            ' class="modal-detail"><i class="fa fa-search-plus" title="查看详情"></i></a>';
                    
                    /* 处理标题 */
                    if (item.title != item.title_sub) {
                        item.title = '<p title="' + item.title + '">' + item.title_sub + '...</p>';
                    }
                    
                    /* 处理行动次数 */
                    item.count_card += ' 次';
                    
                    /* 处理状态 */
                    var str_status = '未知';
                    if (item.status == 0) {
                        str_status = '<font class="text-danger">禁用</font>';
                    } else if (item.status == 1) {
                        str_status = '<font class="text-primary">正常</font>';
                    } else if (item.status == -2) {
                        str_status = '<font class="text-danger">删除待确认</font>';
                    }
                    item.str_status = str_status;
                    
                    /* 处理操作项 */
                    item.action = '<a href="/archiveadmin/content/edit?_id=' + item._id + '" class="btn btn-sm btn-orange" title="编辑" target="_blank">编辑</a>&nbsp;&nbsp;' +
                           '<a href="/archiveadmin/share/edit?_id=' + item._id + '" class="btn btn-xs btn-green" title="授权">授权</a>&nbsp;&nbsp;' +
                            '<a href="' + DOWNLOAD_URL + '?content_id=' + item._id + '" type="button" class="btn btn-xs btn-lightblue" target="_blank">下载</a>';
                    if (item.status == 1) {
                        item.action += '&nbsp;&nbsp;<a href="javascript:;" type="button" class="btn btn-xs btn-red action-select-confirm" data-sn="' + item.sn + '"' + 
                                'data-toggle="modal" data-target="#modal_select_confirm" data-backdrop="static">删除</a>';
                    }
                });
            }
        }),
        loadingHTML: '<span><img src="/static/panel/img/loading.gif"><i class="fa fa-info-sign text-muted" "></i>正在加载……</span>',
        itemsText: '项',
        itemText: '项',
        dataOptions: { pageIndex: 0, pageSize: 20 }
    });
}